//
//  HZComposePictureView.swift
//  HansWeibo
//
//  Created by Hans on 16/8/17.
//  Copyright © 2016年 Hans. All rights reserved.
//

import UIKit
// cell可重用标识符
private let HZComposePictureViewCellID = "HZComposePictureViewCellID"

class HZComposePictureView: UICollectionView {
    
    // 保存image的数组
    var imageArray: [UIImage] = [UIImage]()
    
    // 声明闭包
    var closure:(()->())?
    

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // MARK:-供外界调用的方法
    func addImage(image: UIImage){
        // 显示当前控件
        self.hidden = false
        // 添加到数组中
        imageArray.append(image)
        // 刷新
        reloadData()
    }
    

    // MARK: - 设置视图
    private func setupUI(){
        // 隐藏当前控件
        self.hidden = true
        backgroundColor = UIColor.whiteColor()
        // 注册cell
        registerClass(HZComposePictureViewCell.self, forCellWithReuseIdentifier: HZComposePictureViewCellID)
        // 设置代理
        dataSource = self
        delegate = self
        // 设置layout
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        // cell 间距
        let cellmargin: CGFloat = 5
        // cell 宽高
        let cellWH:CGFloat = (SCREENW - 20 - 2 * cellmargin)/3
        // 设置itemSize
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        // 设置垂直水平间距
        layout.minimumLineSpacing = cellmargin
        layout.minimumInteritemSpacing = cellmargin
    }
    
}


// MARK:- UICollectionViewDataSource
extension HZComposePictureView :UICollectionViewDataSource ,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let count = imageArray.count
        
        if count == 0 || count == 9 {
            return count
        }
        return imageArray.count + 1
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HZComposePictureViewCellID, forIndexPath: indexPath) as! HZComposePictureViewCell
//        cell.backgroundColor = randomColor()
        
        if imageArray.count == indexPath.item {
            
            cell.image = nil
            
        }else{
            // 赋值
            cell.image = imageArray[indexPath.item]
            
            // 实例化闭包
            cell.closure = {[weak self] in
                // 删除指定图片
                self?.imageArray.removeAtIndex(indexPath.item)
                if self?.imageArray.count == 0{
                    // 隐藏当前控件
                    self?.hidden = true
                }
                // 刷新UI
                self?.reloadData()
            }
        }
        
        
        
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        //  如果不是0 不是 9 最后一张图片为+ 号图片
        if imageArray.count == indexPath.item  {
            closure?()
        }
        
    }
    
}

// MARK: -  自定义cell
class HZComposePictureViewCell: UICollectionViewCell {
    
    // 闭包 01
    var closure:(()->())?
    
    // 供外界调用
    var image: UIImage?{
        
        didSet{
            // 赋值
            if image == nil {
                bgImageView.image = UIImage(named: "compose_pic_add")
                bgImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                deleteBtn.hidden = true
            }else{
                bgImageView.image = image
                // 解决cell 复用问题
                bgImageView.highlightedImage = nil
                deleteBtn.hidden = false
            }
        }
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // MARK: - 设置视图
    
    private func setupUI(){
        
        
        // 添加控件
        contentView.addSubview(bgImageView)
        contentView.addSubview(deleteBtn)
        // 设置约束
        bgImageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        deleteBtn.snp_makeConstraints { (make) in
            make.top.trailing.equalTo(contentView)
        }
        
    }
    
    // 按钮事件监听
    func buttonClick(){
        // 03
        closure?()
    }
    
    // 懒加载控件
    private lazy var bgImageView :UIImageView = UIImageView()
    // 删除按钮 
    private lazy var deleteBtn :UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named:"compose_photo_close"), forState: UIControlState.Normal)
        btn.addTarget(self, action: "buttonClick", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    
}


